import axios from "axios";
import qs from "qs";

const root = "/api";
const service = axios.create({
  baseURL: root, // api 的 base_url
  timeout: 5000 // request timeout
});
service.interceptors.request.use(
  config => {
    config.data = qs.stringify(config.data, { arrayFormat: "brackets" });
    config.headers["Content-Type"] = "application/x-www-form-urlencoded";
    return config;
  },
  error => {
    Promise.reject(error);
  }
);

function apiAxios(method, url, params) {
  return new Promise((resolve, reject) => {
    service({
      method: method,
      url: url,
      data: method === "POST" || method === "PUT" ? params : null,
      params: method === "GET" || method === "DELETE" ? params : null
    })
      .then(
        res => {
          if (!res.data.hasOwnProperty("ErrorCode")) {
            resolve(res.data);
            return;
          }
        },
        error => {
          reject(error);
        }
      )
      .catch(error => {
        reject(error);
      });
  });
}
const apiStub = {
  get: (url, params) => {
    return apiAxios("GET", url, params);
  },
  post: (url, params) => {
    return apiAxios("POST", url, params);
  },
  put: (url, params) => {
    return apiAxios("PUT", url, params);
  },
  delete: (url, params) => {
    return apiAxios("DELETE", url, params);
  }
};

export default apiStub;
